define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'inventory/material/index' + location.search,
                    add_url: 'inventory/material/add',
                    edit_url: 'inventory/material/edit',
                    del_url: 'inventory/material/del',
                    multi_url: 'inventory/material/multi',
                    import_url: 'inventory/material/import',
                    table: 'material',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                //search:false,
                showToggle:false,
                fixedColumns: true,
                fixedRightNumber: 2,
                columns: [
                    [
                        {checkbox: true},
                      //  {field: 'id', title: __('Id')},
                       // {field: 'auto_id', title: __('Auto_id')},
                        {field: 'crdname', title:__("crdname"),operate: 'LIKE'},
                        {field: 'order_date', title: __('Order_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'fOrderBillNo', title: __('fOrderBillNo'), operate: 'LIKE'},
                        {field: 'material_code', title: __('Material_code'), operate: 'LIKE'},
                        {field: 'row_id', title: __('Row_id'), operate: 'LIKE'},
                        
                        {field: 'inventory_number', title: __('Inventory_number'), operate: 'LIKE'},
                        {field: 'inv_name', title:__('Inv_name'),operate: 'LIKE'},
                        {field: 'specification', title:__('Specification'),operate: 'LIKE'},
                        /*{field: 'attributes', title:"物料属性",operate: 'LIKE',formatter:function(varl,row,i){
                                return row.inventory?row.inventory.attributes:'';
                            }},*/
                        {field: 'unit', title:__("Unit"),operate: false},
                        {field: 'quantity', title: __('Quantity'), operate:'BETWEEN'},
                        //{field: 'commit_quantity', title: __('Commit_quantity'), operate:'BETWEEN'},
                        {field: 'store_unit', title:__("Store_unit"),operate: false},
                        {field: 'store_quantity', title: __('Store_quantity'), operate:false},
                        //{field: 'fitemsbs', title:__("Fitemsbs"),operate: 'LIKE'},
                        //{field: 'fitemss', title:__("Fitemss"),operate: 'LIKE'},
                        //{field: 'fitemssname', title:__("Fitemssname"),operate: 'LIKE'},
                        //{field: 'cdepcode', title:__("Cdepcode"),operate: 'LIKE'},
                        
                        {field: 'warehouse_name', title:'仓库', operate:'LIKE'},
                        {field: 'shelves_name', title:'拣货路径',operate: 'LIKE'},
                        //{field: 'fPrice', title:__("单价"),operate: false},
                        //{field: 'fAmount', title:__("总价"),operate: false},
                        {field: 'status', title: '状态', searchList: {"0":'关闭',"1":'正常'}, formatter:function(varl,row,i){
                            if(row.status==1){
                                return '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="" data-field="status" data-value="1" data-original-title="点击搜索 正常"><span class="text-success">正常</span></a>';
                            }else{
                                return '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="" data-field="status" data-value="0" data-original-title="点击搜索 关闭"><span class="text-primary">关闭</span></a>';
                            }
                       }},
                        //  {field: 'close_time', title: __('Close_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        //{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'operate', title: __('Operate'), table: table,
                            buttons: [
                                {name: 'detail', text: '详情', title: '详情', icon: 'fa fa-list', classname: 'btn btn-xs btn-primary btn-dialog',url:'inventory/material/edit?flag=print&single=0',}
                            ],
                            events: Table.api.events.operate,
                            formatter:function (value, row, index) {
                                var that = $.extend({},this);
                                var table = $(this.table).clone(true);
                                //后端传之判断是否有编辑、删除操作权限
                                $(table).data('operate-edit',null);
                                //$(table).data('operate-del',null);
                                that.table = table;
                                return Table.api.formatter.operate.call(that,value,row,index);
                            }
                        }
                      //  {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                      //   {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            $('.syn-u8').on('click',function(){
                Toastr.options = {timeOut:15000};
                Toastr.info("数据同步中请稍后....");
                $.post('inventory/material/getData',{type:'kis'},function(e){
                       if(e.code==1){
                         Toastr.options = {timeOut:2000};
                         Toastr.success(e.msg);
                         table.bootstrapTable('refresh');
                       }else{
                         Toastr.error(e.msg);
                       }
                    })
             })
             
             $('.syn-oa').on('click',function(){
                Toastr.info("数据同步中请稍后....");
                $.post('inventory/material/getData',{type:'oa'},function(e){
                       if(e.code==1){
                         Toastr.success(e.msg);
                         table.bootstrapTable('refresh');
                       }else{
                         Toastr.error(e.msg);
                       }
                    })
             })
             
             //打印物料标签
            $('#print-btn').click(function(){
                let list =  table.bootstrapTable('getSelections');
                if(list.length==0){
                    return Toastr.error("请先选择要打印的记录");   
                }
                let ids_arr = []
                let cBatch_arr = []
                for(let i=0;i<list.length;i++){
                    ids_arr.push(list[i].inv_id)
                    cBatch_arr.push(list[i].cBatch)
                }
                Fast.api.open('information/inventory/print?inventory_id='+ids_arr.join(',')+'&cBatch='+cBatch_arr.join(','),'打印物料信息');
            })
             
             //打开新增领料单
            $(document).on("click", ".btn-add-material", function (e, obj) {
            	Backend.api.addtabs("inventory/material/add","新增领料申请") 
            })
            
             //拣货打印
            $(document).on("click", ".btn-print", function (e, obj) {
            	let ids =  Controller.api.selectedids(table);
            	if(!ids.length){
            		Toastr.error("请选择要打印的领料单");
            		return
            	}
            	/*if(ids.length!=1){
            		Toastr.error("请选择要一条记录进行打印");
            		return
            	}*/
            	let ids_arr = []
            	for(let i=0;i<ids.length;i++){
            		if(i>0&&ids[i].material_code!=ids[i-1].material_code){
            			Toastr.error("请选择同一张领料申请单");
            			return 
            		}
            		ids_arr.push(ids[i].id)
            	}
            	Backend.api.open("inventory/material/edit?flag=print&single=1&ids="+ids_arr.join(','),"拣货打印") 
            })
            
            //整单删除
            $('.btn-dels').click(function(){
                let allids =  Controller.api.selectedid(table);
                if(allids.length==0) {
                	Toastr.error("请选择数据");
                	return 
                }
            
              //批量删
              let index = layer.confirm('确定要删除单据，此操作不可逆转？', {
              	  btn: ['确定','关闭'], //按钮
              	  title:'温馨提示'
              }, function(index){
                    layer.close(index);
                    let ids = Table.api.selectedids(table);
                     
                    //隐藏审核按钮，免得再次点击，重复提交
                    //$("#bdeal-btn").addClass('hidden')
                    Fast.api.ajax({
                        url: 'inventory/material/del',
                        data: {ids:allids,'dels':1}
	                      }, function (data) {
	                    	  $("a.btn-refresh").trigger("click");
	                      },function (data) {
	                    	  $("a.btn-refresh").trigger("click");
	                      });
	                });
            })

            //定时器,每60秒刷新一次
            var timer = setInterval(function() {
            	$("a.btn-refresh").trigger("click");
            }, 60*1000);
            
            $("#btn-stop-refresh").on('click',function(){
            	if($("#btn-stop-refresh").html()=='停止刷新'){
            		$("#btn-stop-refresh").html('开启刷新')
            		clearInterval(timer)
            	}else{
            		$("#btn-stop-refresh").html('停止刷新')
            	    timer = setInterval(function() {
                     	$("a.btn-refresh").trigger("click");
                    }, 60*1000);
            	}
            })
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'inventory/material/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'inventory/material/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'inventory/material/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        //物料列表->领料申请单展示页
        add: function () {
        	 // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'inventory/material/inventoryList' + location.search,
                }
            });

            var table = $("#table");

            var numberInput = function (value, row, index) {
            	
            }
            
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                pageSize:15,
                showExport: false,
                showToggle:false,
                showFullscreen:true,
                striped:true,
                columns: [
                    [
                        //{checkbox: true},
                       // {field: 'id', title: __('Id')},
                       // {field: 'shelves_id', title: __('Shelves_id')},
                    	{field: 'kcflag', title: '库存标识', searchList: {'0':'全部',"1":"库存不为0"},visible:false},
                        {field: 'image_url', title: '物料图片', searchList: {'0':'无图',"1":"有图"}, events: Table.api.events.image, formatter: Table.api.formatter.images,width:120,cellStyle: function (value, row, index) {
                        	return {
                        		css: {
                        			"white-space": "nowrap",
                                    "overflow": "hidden",
                                    "max-width":"120px",
                                    }
                        		}}
                        	
                        },
                        {field: 'number', title: __('物料编码'), operate: 'LIKE %...%',sortable: true},
                        {field: 'name', title: __('物料名称'), operate: 'LIKE %...%',sortable: true},
                        {field: 'specification', title: __('规格'), operate: 'LIKE %...%'},
                        //{field: 'attributes', title: __('Attributes'), operate: 'LIKE'},
                        //{field: 'classification_name', title: __('Classification_name'), operate: 'LIKE'},
                       // {field: 'classification_id', title: __('Classification_id')},
                       // {field: 'switch', title: __('Switch'), searchList: {"0":__('Switch 0')," 1":__('Switch 1')},table: table, formatter: Table.api.formatter.toggle},
                        //{field: 'group', title: __('Group'), operate: 'LIKE'},
                        {field: 'unit', title: __('单位'), operate: 'LIKE'},
                        {field: 'iQuantity', title: __('库存'), operate: false},
                        {field: 'nums', title: __('输入数量'), operate: false, formatter:function(value,row,index){
							value = parseFloat(row.nums);
					let str = '<div class="inputNum"><input class="form-control numstyle row_'+row.id+'" min="0" type="number" data-rule="required;range(0~)" style="width:90px" id="' + this.field + '_' + row.id + '" name="' + this.field + '[' + row.id + ']" value="' + value.toFixed(2) + '" placeholder="输入数量" />';
					str+="<button class='btn btn-success' style='' onclick=toAddSum("+row.id+","+row.iQuantity+",'"+row.name+"')>确定</button></div>"
					return str;
						}, width: 120},
                        
                        //{field: 'mbatch', title: __('Mbatch'),searchList: {"0":__('Mbatch 0')," 1":__('Mbatch 1')},formatter: Table.api.formatter.normal},
                        //{field: 'safe_num', title: __('Safe_num')},
                        //{field: 'max_num', title: __('Max_num')},
                        //{field: 'min_num', title: __('Min_num')},
                        //{field: 'source', title: __('Source'), searchList: {"1":__('Source 1')," 2":__('Source  2')}, formatter: Table.api.formatter.normal},
                        //{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                      //  {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                       // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            //打开新增领料单明细
            $(document).on("click", ".btn-pc-material-detail", function (e, obj) {
            	//var warehouse_id = $("#c-warehouse_id").val();
            	top.Backend.api.open('inventory/material/addPcDetail?warehouse_id=2',"查看领料申请",{area:["100%", "100%"],callback:function(flag){//offset:'r',
            		if(flag=='ok'){
            			$(".tip").addClass('hidden')
            		}
            	}}) ;
            })

            $(".search>input").eq(0).addClass('searchtyle')
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        addpcdetail: function () {
            
        	//清空数据
            $(document).on("click", "#toclear", function (e, obj) {
            	let index = layer.confirm('确定要清空数据？', {
            	  	  btn: ['确定','关闭'], //按钮
            	  	  title:'温馨提示'
            	  }, function(index){
            	        layer.close(index);
            	        
            	        Fast.api.ajax({
            	            url: 'inventory/material/clearData',
            	            data: {}
            	            }, function (data) {
            	          	  //$("a.btn-refresh").trigger("click");
            	          	  setTimeout(function(){
            	          		Fast.api.close('ok');
            	          	  },1000);
            	            });
            	      	}, function(){
            	      		//$("a.btn-refresh").trigger("click");
            	      });
            })
            
            //生成领料单
            $(document).on("click", "#tosubmit", function (e, obj) {
            	openUser('submit');
            })
            
            //关闭弹窗
            $(document).on("click", "#toclose", function (e, obj) {
            	Fast.api.close();
            })
            
            $("#oa_item_name_id").data("params", function (obj) {
			    //obj为SelectPage对象
			    return {custom: {field_4:1,field_5: $("#oa_citem_type").val()}};
			});
            
            Controller.api.bindevent();
        },
        edit: function () {
            $(document).on("click", "#c-export", function (e, obj) {
            	Fast.api.ajax({
                    url: 'inventory/material/export',
                    data: {code:$("#c-cPOID-e").val()}
                }, function (data) {
              	  //parent.Toastr.success('添加成功');
                }, function (data,ret) {
                	//Toastr.error(ret.msg);
                		//console.log(ret.msg) 
                	  /*setTimeout(function(){
                	  },10000)*/
                });
            });
            
            $(document).on("click", ".btn-print", function(){
        		$(".widget-body").css("display",'none');
        	    window.print();
        	    $(".widget-body").css("display",'')
        	    Fast.api.close(); // 关闭弹窗
        	});
            
            Controller.api.bindevent();
        },
        api: {
        	selectedids: function (table, current) {
                var options = table.bootstrapTable('getOptions');
                //如果有设置翻页记忆模式
                if (!current && options.maintainSelected) {
                    return options.selectedIds;
                }
                return $.map(table.bootstrapTable('getSelections'), function (row) {
                    return row;
                });
            },
        	bindevent: function () {
                //Form.api.bindevent($("form[role=form]"));
        		Form.api.bindevent($("form[role=form]"),function(data,ret){
            		Toastr.success("操作成功");
            		//关闭新增，打开编辑
            		if(data!=''){
	            		var data = JSON.parse(data);
	            		if(data.action=='add'){
	            			setTimeout(function(){
	            				//top.$("a.btn-refresh").trigger("click");
	            				Fast.api.close('ok'); // 关闭弹窗
	            			},500)
	            			//parent.location.reload();
	            		}
            		}
            		//parent.$("a.btn-refresh").trigger("click");
            		return false;
            	},function(data,ret){
            		Toastr.error(ret.msg);
            		//失败进入
            		/*setTimeout(function(){
        				top.$("a.btn-refresh").trigger("click");
        				Fast.api.close('ok'); // 关闭弹窗
        			},1500)*/
            		return false;
            	},function(success,error){
            		Form.api.submit($("form[role=form]"), success, error);
            		return false;
            	});
            },
            //获取选中的行
            selectedid: function (table, current) {
                var options = table.bootstrapTable('getOptions');
                //如果有设置翻页记忆模式
                if (!current && options.maintainSelected) {
                    return options.selectedIds;
                }
                return $.map(table.bootstrapTable('getSelections'), function (row) {
                    return row[options.pk];
                });
            },
        }
    };
    return Controller;
});
//添加数量
function toAddSum(id = '',iQuantity = 0,name = ''){
	if(id=='')return;
	let nums = 0;
	
	$(".row_"+id).each(function(i,n){
		if($(n).val()!=''){
			nums = $(n).val()
		}
	});

	if(isNaN(nums)){
		Toastr.error(name+"数量输入有误");
		return
	}
	if(nums<=0){
		Toastr.error(name+"数量输入有误");
		return
	}
	if(iQuantity<=0){
		Toastr.error(name+"库存为0");
		return
	}
	if(nums>iQuantity){
		Toastr.error(name+"领取数量大于库存");
		return
	}
	
	var loadindex = layer.load(0); //0代表加载的风格，支持0-2
	Fast.api.ajax({
        url: 'inventory/material/addPcDetail',
        data: {"id":id,"nums":nums}
    }, function (data) {
  	  //parent.Toastr.success('添加成功');
	  setTimeout(function(){
		  //$("#nums_"+id).val('')
			  $(".row_"+id).each(function(i,n){
				if($(n).val()!=''){
					$(n).val('')
				}
			});
			$(".tip").removeClass('hidden')
	  },800)
	  layer.close(loadindex);
    }, function (data,ret) {
    	//Toastr.error(ret.msg);
    		//console.log(ret.msg) 
    	  /*setTimeout(function(){
    		
    	  },10000)*/
    	 layer.close(loadindex);
    });
}
function openUser(flag){
	if($("#oa_type").val()==0){
		Toastr.error('请选择类别');
		return
	}
	if($("#oa_citem_type").val()==0){
		Toastr.error('请选择项目大类');
		return
	}
	if($('#oa_item_name_id').selectPageText()==''){
		Toastr.error('请选择项目');
		return
	}
	if($("#c-basic-textarea").val()=='[]'){
		Toastr.error('请选择物料');
		return
	}
	
	$("#oa_item_name").val($('#oa_item_name_id').selectPageText())
	//打开领料人
	//top.Backend.api.open('information/u8user/index',"选择领料人",{offset: 'r',area:["60%", "80%"],callback:function(row){
	top.Backend.api.open('information/oauser/index',"选择领料人",{offset: 'r',area:["60%", "80%"],callback:function(row){
		let index = layer.confirm('确定要生成领料单至OA平台？', {
      	  	  btn: ['确定','关闭'], //按钮
      	  	  title:'温馨提示'
      	  }, function(index){
      	      layer.close(index);
      	      
      	      $("#user_id").val(row.user_id)
      	      $("#user_name").val(row.user_name)
      	      $("#dept_name").val(row.dept_name)
      	      $("#dept_id").val(row.dept_id)
      	      $("#edit-form").submit()
      	  }, function(){
      		  //点击否
      		  $("#user_no").val('')
    	      $("#user_name").val('')
    	      $("#dept_name").val('')
    	      $("#dept_id").val('')
      	  });
		
    }});
}
function changeItemName(){
	$('#oa_item_name_id').selectPageClear();
}